const mongoose = require('mongoose');

// 考勤模型定义
const attendanceSchema = new mongoose.Schema({
  studentId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Student',
    required: true,
    index: true
  },
  classId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Class',
    required: true,
    index: true
  },
  date: {
    type: Date,
    required: true,
    index: true
  },
  status: {
    type: String,
    required: true,
    enum: ['present', 'absent', 'late', 'excused'],
    default: 'present',
    index: true
  },
  notes: {
    type: String,
    trim: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

// 确保每个学生每天只有一条考勤记录
attendanceSchema.index({ studentId: 1, date: 1 }, { unique: true });

// 更新updatedAt字段的中间件
attendanceSchema.pre('save', function(next) {
  this.updatedAt = Date.now();
  next();
});

// 静态方法：获取学生考勤统计
attendanceSchema.statics.getStudentAttendanceStats = async function(studentId, startDate, endDate) {
  const query = { studentId };
  if (startDate) {
    query.date = { $gte: startDate };
  }
  if (endDate) {
    query.date = query.date || {};
    query.date.$lte = endDate;
  }
  
  const result = await this.aggregate([
    { $match: query },
    {
      $group: {
        _id: null,
        total: { $sum: 1 },
        present: { $sum: { $cond: [{ $eq: ['$status', 'present'] }, 1, 0] } },
        absent: { $sum: { $cond: [{ $eq: ['$status', 'absent'] }, 1, 0] } },
        late: { $sum: { $cond: [{ $eq: ['$status', 'late'] }, 1, 0] } },
        excused: { $sum: { $cond: [{ $eq: ['$status', 'excused'] }, 1, 0] } }
      }
    }
  ]);
  
  return result.length > 0 ? result[0] : null;
};

// 静态方法：获取班级考勤统计
attendanceSchema.statics.getClassAttendanceStats = async function(classId, date) {
  const query = { classId };
  if (date) {
    // 确保查询当天的所有考勤记录
    const startOfDay = new Date(date);
    startOfDay.setHours(0, 0, 0, 0);
    const endOfDay = new Date(date);
    endOfDay.setHours(23, 59, 59, 999);
    query.date = { $gte: startOfDay, $lte: endOfDay };
  }
  
  const result = await this.aggregate([
    { $match: query },
    {
      $group: {
        _id: null,
        totalStudents: { $sum: 1 },
        present: { $sum: { $cond: [{ $eq: ['$status', 'present'] }, 1, 0] } },
        absent: { $sum: { $cond: [{ $eq: ['$status', 'absent'] }, 1, 0] } },
        late: { $sum: { $cond: [{ $eq: ['$status', 'late'] }, 1, 0] } },
        excused: { $sum: { $cond: [{ $eq: ['$status', 'excused'] }, 1, 0] } }
      }
    }
  ]);
  
  return result.length > 0 ? result[0] : null;
};

const Attendance = mongoose.model('Attendance', attendanceSchema);

module.exports = Attendance;